import { Toast, Dialog } from "vant";
import cTitle from "components/title";
import purchaseNotes from "../purchaseNotes/purchaseNotes.vue";
import addressUs from "../addressUs/addressUs";
import yzService from "components/ui_components/yz_service.vue";
export default {
  components: {
    purchaseNotes,
    addressUs,
    cTitle,
    yzService,
    Dialog
  },
  data() {
    return {
      code: "",
      orderShow: false, //开启优惠券弹窗
      orderId: null,
      goodsId: null,
      refundId: null, //售后ID
      addressDetail: "",
      storeName: "", //商户名称
      couponStore: {}, //券码信息
      goodsDetail: {},
      couponList: [], //券码列表
      usableCoupon: [],
      couponCode: "",
      latitude: "",
      longitude: "",
      details: {},
      storeListByGoods: [], //商户列表信息
      total: 0,
      orderType: "shop",
      evaluateType: 0,
      succees: 0,
      //客服插件
      isMiniApp: window.isMiniprogram ? true : false,
      serviceShow: false,
      customerOpen: false,
      cservice: "",
      serviceQRcode: "",
      serviceMobile: "",
      //新加的企业微信数据显示
      clientType: "",
      client: "",
      member_id: "",

      is_show_component: false,
      packages: [],
      purchase: {},
      goodsInfo: {},
      point:{
        lat:"",
        lng:""
      },
      store:[],
      code_list: []
    };
  },
  activated() {
    this.orderId = Number(this.$route.params.order_id);

    let myLoaction = JSON.parse(localStorage.getItem("myLocation"));
    if (!myLoaction) {
      this.fun
        .getLocation()
        .then(res => {
          this.point = res.point;
          this.getDetails();
        })
        .catch(err => {
          console.log(err);
          this.getDetails();
        });
    } else {
      this.point = myLoaction ? myLoaction.point : {};
      this.getDetails();
    }
  },
  methods: {
    async getDetails() {
      let json = { order_id: this.orderId,longitude:this.point.lng,latitude:this.point.lat}
      let { result, msg, data } = await $http.post("plugin.local-life.api.order-detail.index",json, "");
      if (result) {
        console.log(data, "data===");
        let code_list = data.code.filter(item => !item.has_one_verify_detail);
        this.goodsInfo = data;
        this.store = data.store;
        this.couponList = data.code;
        this.code_list = code_list;
        this.packages = data.goods.package;
        this.purchase = data.goods.purchase;
        this.$nextTick(() => {
          this.is_show_component = true;
        });
        this.serviceDetail();
        this.code_list.length !== 0 && this.refreshCode();
      } else {
        this.$toast(msg);
      }
    },
    orderstateOn(params) {
      this.getorderState(params);
    },
    getorderState(params) {
      let {value, id, refundId, api,itemBtn,item} = params;
      let query = {
        5:() => {   //确认签收
          this.$dialog
        .confirm({ message: itemBtn.name })
        .then(() => {
          this.confirmOrder_request(id, itemBtn);
        })
        .catch(() => {});
        },
        18:() => {   //确认签收
          this.$router.push(
            this.fun.getUrl("aftersales", {
              refund_id: refundId
            })
          );
        },
        13:() => {   //申请售后
          this.$router.push(
            this.fun.getUrl(
              "refund",
              {
                order_id: id,
                order_type: 1
              },
              { value: value ,plugin : 'local_life'}
            )
          );
        },
        41: `${api}`, //客服
      };
      if (value.toString() === "12") {
        this.$dialog.confirm({
          title: "提示",
          message: "确定删除该订单?"
        })
          .then(() => {
            this.deletePay(item.id, api);
          })
          .catch(() => {
            // on cancel
          }); //删除订单
      } else if (value == 8 || value == "snatch_regiment_express") {
        this.checklogistics(item, itemBtn);
      } else if (value.toString() === "41") {
        if (query[value]) {
          window.location.href = query[value];
        } else { 
          this.$toast('请设置客户链接');
        }
      }
      else {
        let paramsObj = query[value];
        if(paramsObj) {
          return paramsObj.call(this);
        } else {
          console.log("获取未知按钮状态数据失败");
        }
      }
    },
    cancelPay(id, api) {
      let json = {
        order_id: id
      };
      $http.post(api, json, "正在获取").then(
        response => {
          if (response.result == 1) {
            Toast(response.msg);
            this.storeorderDetails();
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
    copyCode() {
      Toast("复制成功");
    },
    onError() {
      Toast("复制成功");
    },
    serviceDetail() {
      $http.post("goods.customer-service.index", {}, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            this.cservice = res.cservice;
            this.serviceQRcode = res.service_QRcode;
            this.serviceMobile = res.service_mobile;
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          console.log(response);
        }
      );
    },
    getRandomElement(arr) {
      // 生成一个随机索引
      const randomIndex = Math.floor(Math.random() * arr.length);
      // 使用这个随机索引从数组中抽取一个元素
      return arr[randomIndex].code;
    },
    async refreshCode() {
      let json = { code: this.getRandomElement(this.code_list), order_id: this.$route.params.order_id };
      let { result, msg, data } = await $http.post("plugin.local-life.api.order.show-code", json, ".");
      if (result) {
        this.code = data.code;
      } else {
        this.$toast(msg);
      }
    },
    shopNavTo() {
      this.$router.push(this.fun.getUrl("local_life_apply_store", { goods_id: this.goodsInfo.goods.goods_id }));
    },
    onClose() {
      this.orderShow = false;
    },
    onQrcode() {
      this.orderShow = true;
    },
    evaluateBtn(storeName) {
      this.$router.push(
        this.fun.getUrl(
          "conevaluate",
          {},
          {
            orderId: this.orderId,
            type: 1,
            storeName: storeName
          }
        )
      );
    },
    refundBtn() {
      this.$router.push(
        this.fun.getUrl(
          "refundOrder",
          {},
          {
            orderId: this.orderId,
            type: 2,
            orderType: 1
          }
        )
      );
    },
    afterSaleBtn() {
      this.$router.push(
        this.fun.getUrl(
          "refundProcess",
          {},
          {
            refundId: this.refundId
          }
        )
      );
    },
    closePop() {
      this.serviceShow = false;
    },
    clickChat() {
      let setServicePlugin = this.fun.isTextEmpty(this.serviceMobile) && this.fun.isTextEmpty(this.serviceQRcode);
      if (this.fun.isTextEmpty(this.cservice) && setServicePlugin) {
        return this.$toast("抱歉，暂未设置客服信息");
      }
      if (!this.fun.isTextEmpty(this.cservice) && setServicePlugin) {
        //只设置了客服链接，直接跳转
        if (this.cservice && this.cservice.indexOf("chatWindow") >= 0) {
          window.location.href = this.cservice + "&goods_id=" + this.$route.params.id;
        } else {
          window.location.href = this.cservice;
        }
        return;
      }
      this.serviceShow = true;
    }
  }
};
